<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiFormTemplatesApi } from '#/api/ai/form/formTemplates';
import type { AiFormVariablesApi } from '#/api/ai/form/formVariables';

import { nextTick, ref } from 'vue';

import { confirm, Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteFormVariables,
  deleteFormVariablesList,
  exportFormVariables,
  getFormVariablesPage,
} from '#/api/ai/form/formVariables';
import { $t } from '#/locales';

import { FormDesignGridColumns, FormDesignGridFormSchema } from '../data';
import Detail from './FormDesignDetail.vue';
import Form from './FormDesignForm.vue';

const emit = defineEmits(['success']);
// 当前模板
const formTempl = ref<AiFormTemplatesApi.FormTemplates>();
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    drawerApi.lock();
    try {
      // 关闭并提示
      await drawerApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      drawerApi.unlock();
    }
  },

  async onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const data = drawerApi.getData<AiFormTemplatesApi.FormTemplates>();
    if (!data) return;
    formTempl.value = data;

    await nextTick(); // 等待 Grid 挂载
    await gridApi.reload();
  },
});

/** 刷新表格 */
function handleRefresh() {
  gridApi.reload();
}

/** 创建表单参数 */
function handleCreate() {
  formModalApi.setData({ formId: formTempl.value.id }).open();
}

/** 编辑表单参数 */
function handleEdit(row: AiFormVariablesApi.FormVariables) {
  formModalApi.setData(row).open();
}

/** 查看表单参数 */
function handleDetail(row: AiFormVariablesApi.FormVariables) {
  detailModalApi.setData(row).open();
}

/** 删除表单参数 */
async function handleDelete(row: AiFormVariablesApi.FormVariables) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
  });
  try {
    await deleteFormVariables(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 批量删除表单参数 */
async function handleDeleteBatch() {
  await confirm($t('ui.actionMessage.deleteBatchConfirm'));
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deletingBatch'),
    duration: 0,
  });
  try {
    await deleteFormVariablesList(checkedIds.value);
    checkedIds.value = [];
    message.success({
      content: $t('ui.actionMessage.deleteSuccess'),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);

function handleRowCheckboxChange({
  records,
}: {
  records: AiFormVariablesApi.FormVariables[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出表格 */
async function handleExport() {
  const data = await exportFormVariables(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '表单参数.xls', source: data });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: FormDesignGridFormSchema(),
  },
  gridOptions: {
    id: 'FormVariables-grid',
    columns: FormDesignGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getFormVariablesPage(
            {
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              formId: formTempl.value.id,
              ...formValues,
            },
            false,
            false,
          );
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<AiFormVariablesApi.FormVariables>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</script>

<template>
  <Drawer title="设计表单" class="w-[80%]">
    <Page auto-content-height>
      <FormModal @success="handleRefresh" />
      <DetailModal @success="handleRefresh" />
      <Grid table-title="表单参数列表">
        <template #toolbar-tools>
          <TableAction
            :actions="[
              {
                label: $t('ui.actionTitle.create', ['表单参数']),
                type: 'primary',
                icon: ACTION_ICON.ADD,

                onClick: handleCreate,
              },
              {
                label: $t('ui.actionTitle.export'),
                type: 'primary',
                icon: ACTION_ICON.DOWNLOAD,

                onClick: handleExport,
              },
              {
                label: $t('ui.actionTitle.deleteBatch'),
                type: 'primary',
                danger: true,
                icon: ACTION_ICON.DELETE,
                disabled: isEmpty(checkedIds),

                onClick: handleDeleteBatch,
              },
            ]"
          />
        </template>

        <template #actions="{ row }">
          <TableAction
            :actions="[
              {
                label: '查看',
                type: 'link',
                icon: ACTION_ICON.VIEW,

                onClick: handleDetail.bind(null, row),
              },
              {
                label: $t('common.edit'),
                type: 'link',
                icon: ACTION_ICON.EDIT,

                onClick: handleEdit.bind(null, row),
              },
              {
                label: $t('common.delete'),
                type: 'link',
                danger: true,
                icon: ACTION_ICON.DELETE,

                popConfirm: {
                  title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                  confirm: handleDelete.bind(null, row),
                },
              },
            ]"
          />
        </template>
      </Grid>
    </Page>
  </Drawer>
</template>
